<?php
namespace tp5_lib\user\controller;

use tp5_lib\common\controller\BaseController;
use tp5_lib\user\model\UserModel;
use tp5_lib\user\logic\UserLogic;
use tp5_lib\user\logic\UserModule;
use think\facade\Session;
use think\facade\Request;

/**
 * 登录控制器
 * 实现登录、注册、找回密码、绑定手机号等功能
 * 处理登录之后跳转到指定页面的行为
 * 
 * @property UserModel $model 用户模型
 * @property UserLogic $logic 用户逻辑
 */
class BaseLoginController extends BaseController
{
    /**
     * 自动登录
     * *这个方法是在入口文件里直接调用的，所以需要用到`think\facade\Request`类，而不能直接用`request`属性
     * 检查是否有登录参数
     * 检查是否是在特定的浏览器中
     */
    public function auto()
    {
        /** @var Request $request */
        if( !Session::get("user") && isset($_SERVER["HTTP_USER_AGENT"]) ){
            $module=new UserModule();
            if($config=$module->read("user")){
                $list=$config["list"];
                $ua=$_SERVER["HTTP_USER_AGENT"];
                foreach($config["monopoly"] as list($id,$monopoly)){
                    if(preg_match($monopoly,$ua)){
                        $method=$list[$id];
                        if(!preg_match("/({$method["module"]}|login)/",$_SERVER["REQUEST_URI"])){
                            $url=url($method["path"]);
                            $request=Request::instance();
                            $url.= "?redirect_url=" . $request->url();
                            $this->redirect($url);
                        }
                    }
                }
            }
        }
    }
    /**
     * 列出可用的第三方登录
     */
    protected function outside()
    {
        $module=new UserModule();
        if(!$config=$module->read("user")){
            return [];
        }
        $list=$config["list"];
        $ua=$_SERVER["HTTP_USER_AGENT"];
        foreach($config["monopoly"] as list($id,$monopoly)){
            if(preg_match($monopoly,$ua)){
                return [$list[$id]];
            }
        }
        //除了微信/企业微信/支付宝内置的浏览器之外的手机浏览器/PC端浏览器
        $result=[];
        if($this->request->isMobile()){
            foreach($config["mobile"] as $id){
                $result[]=$list[$id];
            }
        }
        else{
            foreach($config["pc"] as $id){
                $result[]=$list[$id];
            }
        }
        return $result;
    }
    /**
     * 标记登录成功后要跳转的页面
     */
    protected function markRedirectUrl()
    {
        $url=input("redirect_url","");
        // if(!$url && $referer=$this->request->server('HTTP_REFERER')) $url=$referer;
        if($url){
            $name=static::class.":redirect_url";
            session($name,$url);
        }
    }
    /**
     * 登录成功后跳转到指定页面
     */
    protected function loginRedirect($user,$msg="")
    {
        //检查是否绑定手机号
        if(empty($user["mobile"])){
            session("bind_mobile_user_id",$user["id"]);
            $this->redirect("user/login/bindMobile");
        }
        $this->doLoginRedirect($msg);
    }
    /**
     * 登陆后跳转
     * 可以跳过验证手机号的步骤
     */
    protected function doLoginRedirect($msg)
    {
        $name=static::class.":redirect_url";
        if($url=session($name)){
            session($name,null);
        }
        else{
            $url=url("user/index/index");
        }
        if($msg){
            $this->success($msg,$url);
        }
        else{
            $this->redirect($url);
        }
    }
    public function __get($name)
    {
        if($name === "model"){
            if(empty($this->_model)){
                $this->_model=new UserModel();
            }
            return $this->_model;
        }
        elseif($name === "logic"){
            if(empty($this->_logic)){
                $this->_logic=new UserLogic();
            }
            return $this->_logic;
        }
    }
    /**
     * 绑定手机号
     */
    public function bindMobile()
    {
        $this->markRedirectUrl();
        $template = $this->request->isMobile() ? "user@public/mobile/bindMobile" : "user@public/pc/bindMobile" ;
        return $this->fetch($template);
    }
    /**
     * @api
     */
    public function doBindMobile()
    {
        $data=input();
        $result=$this->validate($data,["mobile"=>"require","code"=>"require"]);
        if(is_string($result)){
            $this->error($result);
        }
        $user_id=session("bind_mobile_user_id");
        if(!$user_id){
            $this->error("用户未登录","login");
        }
        $user=$this->logic->model->db()->where(["id"=>$user_id])->find();
        if(!$user=$this->logic->bindMobile($user,$data["mobile"],$data["code"])){
            $this->error($this->logic->getError());
        }
        $this->loginRedirect($user,"绑定成功，正在跳转");
    }
    public function jumpBindMobile()
    {
        $this->doLoginRedirect("游客身份访问");
    }
}
